package com.leo.netty.heartbeat;

import com.leo.netty.chart.ChartServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author du
 */
public class HeartbeatServer {
    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))  // BossGroup加一个日志处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            /**
                             * 1. netty提供处理空闲状态的处理器
                             * 2. long readerIdleTime: 指定时间内没有读事件, 则发送一个心跳检测包
                             *    long writerIdleTime: 指定时间内没有写事件, 则发送一个心跳检测包
                             *    long allIdleTime   : 指定时间内没有读/写事件, 则发送一个心跳检测包
                             *
                             * 3. 空闲事件发生时, 会触发IdleStateEvent空闲事件, 传递给pipeline的下一个
                             *    handler进行处理 (通过调用下一个handler的 userEventTriggered方法, 此方法中去处理)
                             */
                            ch.pipeline().addLast(new IdleStateHandler(
                                    3,
                                    5,
                                    7,
                                    TimeUnit.SECONDS));
                            ch.pipeline().addLast(new HeartbeatHandler());
                            System.out.println("Channel 初始化完毕.");
                        }
                    });

            b.bind(8888).sync().addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    System.out.println("监听端口8888成功");
                } else {
                    System.out.println("监听端口8888失败");
                }
            }).channel().closeFuture().sync(); //监听关闭

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    static class HeartbeatHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent event = (IdleStateEvent) evt;
                String eventType = null;
                switch (event.state()) {
                    case READER_IDLE:
                        eventType = "读空闲";
                        break;
                    case WRITER_IDLE:
                        eventType = "写空闲";
                        break;
                    case ALL_IDLE:
                        eventType = "读/写空闲";
                        break;
                }
                System.out.println(ctx.channel().remoteAddress() + eventType);
            }
        }
    }
}
